<template>
  <div class="accredit" v-if="!accredit">
    <div class="corporation">
      <h1 class="logo">
        <img src="http://mobuz-mp.gz.bcebos.com/matter/mp_logo.png" alt="悦器社">
      </h1>
      <h2 class="corporation-name">悦器社</h2>
      <p>极悦信息科技有限公司</p>
    </div>
    <div class="setting">
      <div class="tell">该程序将获取以下授权：</div>
      <p class="reminder">获得你的公开信息（昵称、头像等）</p>
    </div>
    <div class="accredit-btn">
      <button @click="cancelAccredit()">取消</button>
      <button open-type="getUserInfo" lang="zh_CN" @getuserinfo="getuserinfo">确定</button>
    </div>
    <!-- <a @click="uploadImg()">测试</a> -->
  </div>
</template>

<script>
import qcloud from "../../../node_modules/wafer2-client-sdk/index.js";
import { checkStudent , obtainUserinfo ,preserveUserinfo, amendUserinfo,obtainJudgeConduct} from "@/config/api";
import { obtainAccreditLoginFlag, showMessager } from "@/config/wUtils";
import { baseUrl } from "@/config/env";
import { triggerSocketWacthDadge } from "@/config/vuexUtils";
// import { uploadMultimedia } from "@/config/mUtils"
export default {
    data() {
        return {
            userInfo: {},
            accredit: true
        };
    },
    async mounted() {
        //  wx_vipcn 公众号推送的模板点开 1收到的评论 2收到的留言  删除公众号推送的数据
        wx.removeStorageSync("wx_vipcn");
        wx.removeStorageSync("wx_vipcn_batch_id");
        wx.removeStorageSync("wx_vipcn_student_id");
        
       


        await this.getUserData();
        if (this.$root.$mp.query.id) {
            showMessager (this.$root.$mp.query.id)
        }
    },
    methods: {
        // 分享判断用户行为
        async shareJudgeConduct () {
            // ios 使用 小程序 购买
            console.log(this.$root.$mp.query, '路由')
           
            if (this.$root.$mp.query && this.$root.$mp.query.operation_state === '1') {
                // 本地用户信息
                this.userInfo = wx.getStorageSync("userInfo");
                console.log(this.userInfo, '.....本地用户信息')
                const batch_id = this.$root.$mp.query.batch_id
                const type_id = this.$root.$mp.query.type_id
                const union_id = this.$root.$mp.query.union_id
                const terrace_state = this.$root.$mp.query.terrace_state
                const operation_state = this.$root.$mp.query.operation_state
                const nickName = this.$root.$mp.query.nickName
                const inviteCode = this.$root.$mp.query.inviteCode
                const open_id = this.userInfo.openId
                wx.redirectTo({ url: '../coursePayment/main?batch_id='+batch_id+'&type_id='+type_id+'&union_id='+union_id+'&openId='+open_id+'&terrace_state='+terrace_state+'&operation_state='+operation_state+'&nickName='+nickName+'&inviteCode='+inviteCode})
                return;
            } 
            let userInfo = wx.getStorageSync("userInfo");
            let {batch_id,section_id} = this.$root.$mp.query;
            await obtainJudgeConduct(this.userInfo['unionId'],batch_id)
                .then(res => {
                    console.log(res,'分享判断用户行为')
                    if (res.status == 200) {
                        // 1 课程详情   2 课堂  3课程介绍页
                        if (res.data['status'] == 1) {
                            wx.redirectTo({ url: '../courseCircumstance/main?batch_id='+batch_id+'&section_id='+section_id+'&student_id='+res.data['studentId']+'&terrace_state=2'})
                        } else if (res.data['status'] == 2) {
                            this.getCheckStudent()
                        } else if (res.data['status'] == 3) {
                            wx.redirectTo({ url: "../courseReferral/main" });
                        }
                    }
                })
        },
        // 取消授权
        cancelAccredit () {
            console.log('退出小程序')
            wx.navigateBack({
                delta: 9
            })

        },
        // 登录
        async getuserinfo() {
            const session = await qcloud.Session.get();

            if (session) {
                // 第二次登录
                // 或者本地已经有登录态
                // 可使用本函数更新登录态
                await qcloud.setLoginUrl(baseUrl + "/weapp/login");
                await qcloud.loginWithCode({
                    success: res => {
                        this.userInfo = res;
                        wx.setStorageSync("userInfo", res);
                        // this.getCheckStudent();
                        if (this.$root.$mp.query.terrace_state == 2) {
                            console.log('卡片*****',this.$root.$mp.query)
                            this.shareJudgeConduct();
                        } else {
                            this.getCheckStudent();
                        }
                    },
                    fail: err => {
                        console.error(err);
                        showMessager("登录错误");
                    }
                });
            } else {
                // 首次登录
                await qcloud.setLoginUrl(baseUrl + "/weapp/login");
                await qcloud.login({
                    success: res => {
                        this.userInfo = res;
                        // showMessager('登录成功3333')
                        // console.log('登录成功11111111111', res)
                        wx.setStorageSync("userInfo", res);
                        // this.getCheckStudent();
                        if (this.$root.$mp.query.terrace_state == 2) {
                            console.log('卡片',this.$root.$mp.query)
                            this.shareJudgeConduct();
                        } else {
                            this.getCheckStudent();
                        }
                        // wx.navigateTo({ url: '../courseReferral/main' });
                    },
                    fail: err => {
                        console.log("退出授权");
                        console.error(err);
                        wx.navigateBack();

                        // showModal("登录错误", err.message);
                    }
                });
                console.log("请求数据333");
            }
        },
        // 判断是否授权过
        async getUserData() {
            // 先获取用户信息
            await obtainAccreditLoginFlag()
                .then(res => {
                    // res 返回true和false
                    console.log("是否授权", res);
                    // 本地用户信息
                    this.userInfo = wx.getStorageSync("userInfo");
                    console.log(this.userInfo, "信息");
                    if (res) {
                        this.accredit = true;
                        if (this.$root.$mp.query.terrace_state == 2) {
                            console.log('卡片.......',this.$root.$mp.query)
                            this.shareJudgeConduct();
                        } else {
                            this.getCheckStudent();
                        }
                    }
                })
                .catch(err => {
                    console.error(err);
                    this.accredit = false;
                });
        },
        async getCheckStudent() {
            console.log(this.$root.$mp.query, '....this.$root.$mp.query')
            // 校验用户购买情况
            await checkStudent(this.userInfo.unionId,this.userInfo.openId)
                .then( async res => {
                    console.log("学员情况", res);
                    if (res.status === 200) {
                        // 获取用户信息
                        await obtainUserinfo(this.userInfo.openId, this.userInfo.unionId)
                            .then(async res1 => {
                                console.log(res1,'......获取用户信息')
                                if (res1.status === 403) { // 没有该用户
                                    // 本地存储学员的批次ID
                                    wx.setStorageSync("batch_id", res.data.batch_id);
                                    // 学员ID
                                    wx.setStorageSync("student_id", res.data.student_id);
                                    // 个人中心引导页的状态（索引）
                                    wx.setStorageSync("guide_state", 0);
                                    // 保存用户信息
                                    await preserveUserinfo(this.userInfo.openId,res.data.batch_id, res.data.student_id)
                                } else if (res1.status === 200)  {  // 获取用户状态
                                    // 本地存储学员的批次ID
                                    wx.setStorageSync("batch_id", res1.data.batch_id);
                                    // 学员ID
                                    wx.setStorageSync("student_id", res1.data.student_id);
                                    // 设置 个人中心引导页的状态（索引）
                                    wx.setStorageSync("guide_state", res1.data.guide_state);
                                } else {
                                    // 本地存储学员的批次ID
                                    wx.setStorageSync("batch_id", res.data.batch_id);
                                    // 学员ID
                                    wx.setStorageSync("student_id", res.data.student_id); 
                                    // 个人中心引导页的状态（索引）
                                    wx.setStorageSync("guide_state", 0);
                                }
                            })
                            .catch(err1 => {
                                // 本地存储学员的批次ID
                                wx.setStorageSync("batch_id", res.data.batch_id);
                                // 学员ID
                                wx.setStorageSync("student_id", res.data.student_id); 
                                // 个人中心引导页的状态（索引）
                                wx.setStorageSync("guide_state", 0);
                                console.error('err1:',err1);
                            })
                        // 超级用户
                        wx.setStorageSync("super_user", res.data.super_user);
                        // 消息推送 进入
                        if (this.$root.$mp.query.batch_id && this.$root.$mp.query.student_id) {
                            // 引导状态
                            let guideState = wx.getStorageSync('guide_state')? wx.getStorageSync('guide_state'): 0
                            // 修改 用户信息
                            let personalState = await amendUserinfo(this.userInfo.openId, this.$root.$mp.query.batch_id, this.$root.$mp.query.student_id, guideState)
                            if (personalState.status === 200) {
                                wx.setStorageSync('student_id', this.$root.$mp.query.student_id)
                                wx.setStorageSync('batch_id', this.$root.$mp.query.batch_id)
                                wx.setStorageSync('super_user', personalState.data.super_user)  
                                wx.setStorageSync('plan_state', 1)
                            }   
                        }   

                        // 微信公众号卡片打开详情 步骤1：判断是否存在跳转元素 步骤2：设置好之后跳转到“今日课程” 步骤3：“今日课程”界面判断app的对象元素（batch_id && section_id && wechatGoto）决定是否跳转
                        // let {batch_id,section_id , wechatGoto,student_id} = this.$root.$mp.query
                        // if (batch_id && section_id && wechatGoto && student_id) {
                        //     let app = getApp();       
                        //     app.wechatGoto = true;
                        //     app.section_id = section_id;
                        //     app.batch_id = batch_id;
                        //     // 保存用户信息
                        //     await preserveUserinfo(this.userInfo.openId,res.data.batch_id, res.data.student_id)
                        // }
                        // 用户已购买课程 返回到“今日课程”
                        wx.switchTab({ url: "../dengesCourse/main" });
                    } else {
                        // 没有购买过课程 返回到首页引导用户购买
                        wx.redirectTo({ url: "../courseReferral/main" });
                    }
                })
                .catch(err => {
                    console.log(err);
                    // 错误也要到首页
                    wx.redirectTo({ url: "../courseReferral/main" });
                });
        },

        // // 上传 -- 图片
        // async uploadImg() {
        //     let self = this;
        //     wx.chooseImage({
        //         count: 1, // 默认9
        //         sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
        //         sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
        //         async success(res) {
        //             // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        //             // var tempFilePaths = res.tempFilePaths
        //             await uploadMultimedia(res.tempFilePaths[0],"operation/image/" )
        //               .then(res1 => {
        //                 console.log(res1,'上传 -- uploadKey')
        //               })
        //               .catcg( err => {
        //                 console.error(err,'上传 -- uploadKey -- 失败')
        //               })
        //             // console.log(uploadKey, "上传 -uploadKey- 图片");
        //         }
        //     });
        // }
    },
    // 切换页面
    onUnload () {
        triggerSocketWacthDadge()
    },
};
</script>

<style lang="less" scoped>
.accredit {
    border-top: 1rpx solid #eaeaea;
    .corporation {
        margin: 0 auto;
        width: 582rpx;
        padding: 61rpx 0 117rpx;
        border-bottom: 1rpx solid #eaeaea;
        .logo {
            margin: 0 auto 36rpx;
            display: block;
            width: 175rpx;
            height: 175rpx;
            border-radius: 8rpx;
            overflow: hidden;
            img {
                display: block;
                width: 100%;
                height: 100%;
            }
        }
        h2.corporation-name {
            font-family: PingFangSC-Regular;
            font-size: 34rpx;
            color: #333333;
            letter-spacing: 0.69rpx;
            text-align: center;
            line-height: 1;
            margin-bottom: 30rpx;
        }
        p {
            font-family: PingFangSC-Regular;
            font-size: 24rpx;
            color: #999999;
            letter-spacing: 0.48rpx;
            text-align: center;
            line-height: 1;
        }
    }
    .setting {
        margin: 0 auto;
        width: 582rpx;
        .tell {
            font-family: PingFangSC-Regular;
            font-size: 26rpx;
            color: #333333;
            letter-spacing: 0.53rpx;
            line-height: 1;
            padding: 32rpx 0 36rpx;
        }
        .reminder {
            padding-left: 29rpx;
            font-family: PingFangSC-Regular;
            font-size: 22rpx;
            color: #999999;
            letter-spacing: 0.44rpx;
            position: relative;
            &::before {
                content: "";
                position: absolute;
                left: 0;
                top: 50%;
                margin-top: -5rpx;
                width: 10rpx;
                height: 10rpx;
                background-color: #ee3a29;
                border-radius: 50%;
            }
        }
    }
    .accredit-btn {
        margin: 72rpx auto 0;
        width: 582rpx;
        font-size: 0;
        text-align: center;
        button {
            display: inline-block;
            width: 220rpx;
            height: 75rpx;
            line-height: 75rpx;
            font-family: PingFangSC-Regular;
            font-size: 28rpx;
            color: #ffffff;
            letter-spacing: 0.44rpx;
            text-align: center;
            background: #d8d8d8;
            border-radius: 10rpx;
            &::after {
                border: none;
            }
            &:nth-child(1) {
                background: #d8d8d8;
                margin-right: 100rpx;
            }
            &:nth-child(2) {
                background-image: linear-gradient(
                    -90deg,
                    #fe7a72 0%,
                    #ffb497 100%
                );
                border-radius: 10rpx;
            }
        }
    }
}
</style>
